﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json.Linq;
using LiteDb;

namespace DidaManager.Native.Network
{
    public class OrayManager
    {
        public OrayManager()
        {
        }

        public string ComposeUrl(string url, string ip, uint port)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url), "URL cannot be null or empty.");
            }
            return $"http://{ip}:{port}{url}";
        }

        public void GetIpAndPort(object param, out string ip, out uint port)
        {
            var jsonString = param?.ToString();
            if (string.IsNullOrEmpty(jsonString))
            {
                ip = "";
                port = 0;
                return;
            }

            var jObject = JObject.Parse(jsonString);
            if (jObject == null)
            {
                ip = "";
                port = 0;
                return;
            }

            jObject.TryGetValue("ip", out var ipToken);
            jObject.TryGetValue("port", out var portToken);
            ip = ipToken?.ToString() ?? "";
            port = portToken != null ? Convert.ToUInt32(portToken) : 0;
        }

        public object GetOrayGetSn(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_get_sn is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteGetSnUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_get_sn URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);

                // Check if response.Content is null before parsing
                if (string.IsNullOrEmpty(response.Content))
                {
                    return ApiResponse.Fail("响应内容为空，无法解析SN");
                }
    
                JObject json = JObject.Parse(response.Content);
                string sn = "";
                json.TryGetValue("sn", out var snToken);
                if (snToken != null)
                {
                    sn = snToken.ToString();
                }
                return ApiResponse.Success(sn, "获取SN成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "获取SN失败");
            }
        }

        public object GetOrayRestart(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_restart is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteRestartUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_restart URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return ApiResponse.Fail("重启失败");
                }

                return ApiResponse.Success(true,"重启成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "重启失败");
            }
        }

        public object GetOrayReset(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_reset is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteResetUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_reset URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return ApiResponse.Fail("重置失败");
                }
                return ApiResponse.Success(true,"重置成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "重置失败");
            }
        }

        public object GetOrayStart(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_start is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteStartUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_start URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return ApiResponse.Fail("启动失败");
                }
                return ApiResponse.Success(true, "启动成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "启动失败");
            }
        }

        public object GetOrayStop(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_stop is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteStopUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_stop URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return ApiResponse.Fail("停止失败");
                }
                return ApiResponse.Success(true, "停止成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "停止失败");
            }
        }

        public object GetOrayStatus(object param)
        {
            string ip = "";
            uint port = 0;
            GetIpAndPort(param, out ip, out port);
            if (string.IsNullOrEmpty(ip) || port == 0)
            {
                return ApiResponse.Fail("获取IP和端口失败");
            }

            // Ensure _url.remote_status is not null before calling ComposeUrl
            var url = NetworkConfig.Instance.GetRemoteStatusUrl();
            if (string.IsNullOrEmpty(url))
            {
                return ApiResponse.Fail("remote_status URL未配置");
            }

            try
            {
                var url_new = ComposeUrl(url, ip, port);
                var response = HttpManager.Get(url_new);

                // Check if response.Content is null before parsing
                if (string.IsNullOrEmpty(response.Content))
                {
                    return ApiResponse.Fail("响应内容为空，无法解析状态");
                }
    
                JObject json = JObject.Parse(response.Content);
                string status = "";
                json.TryGetValue("status", out var statusToken);
                if (statusToken != null)
                {
                    status = statusToken.ToString();
                }
                return ApiResponse.Success(status, "获取状态成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(ex.Message, "获取状态失败");
            }
        }

    }
}
